package com.duowei.diandan.fragment;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.duowei.diandan.R;
import com.duowei.diandan.adapter.OrderAdapter;
import com.duowei.diandan.app.InitManager;
import com.duowei.diandan.app.OrderList;
import com.duowei.diandan.bean.food.OrderItem;
import com.duowei.diandan.bean.food.Single;
import com.duowei.diandan.constant.ChoiceType;
import com.duowei.diandan.constant.OrderMode;
import com.duowei.diandan.constant.Settings;
import com.duowei.diandan.databinding.OrderFragmentBinding;
import com.duowei.diandan.db.entry.Jyxmsz;
import com.duowei.diandan.db.entry.Wmlsbjb;
import com.duowei.diandan.event.ToastEvent;
import com.duowei.diandan.fragment.dialog.PromptDialogFragment;
import com.duowei.diandan.sql.OrderCommit;

import org.greenrobot.eventbus.EventBus;

import java.util.List;
import java.util.Locale;
import java.util.Observer;

public class OrderFragment extends BaseFragment {
    public static final String TAG = "OrderFragment";

    private OrderFragmentBinding mBinding;
    private OrderAdapter mAdapter;

    private Handler mHandler = new Handler();

    /** 是否需要滚动到底部 */
    private boolean mScroll = false;

    private boolean mFromCloud = false;

    private Observer mOrderObserver = (o, arg) -> {
        refreshData(OrderList.getInstance().getOrderItemList());
    };


    private TextView.OnEditorActionListener mScanOnEditorActionListener = (v, actionId, event) -> {
        if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
            mScroll = true;

            // 重记倒计时
            InitManager.getInstance().setRestTouchTime();

            // 扫描处理
            String scanText = v.getText().toString();

            Jyxmsz jyxmsz = getDb().jyxmszDao().findByTm(scanText);
            if (jyxmsz == null) {
                EventBus.getDefault().post(new ToastEvent("未发现扫描的单品", false));
            } else {
                EventBus.getDefault().post(new ToastEvent(jyxmsz.getXmmc() + "+1"));
                OrderList.getInstance().addSingle(new Single(jyxmsz), null, null);
            }

            v.setText(null);

            mHandler.postDelayed(() -> {
                mBinding.scanEditText.requestFocus();
            }, 100);

            return true;
        } else {
            return false;
        }
    };

    public static OrderFragment newInstance(boolean fromCloud) {

        Bundle args = new Bundle();
        args.putBoolean("fromCloud", fromCloud);

        OrderFragment fragment = new OrderFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mFromCloud = getArguments().getBoolean("fromCloud");
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_order, container, false);
        return mBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(),
                LinearLayoutManager.VERTICAL, false);
        mBinding.recyclerView.setLayoutManager(layoutManager);

        if (Settings.ORDER_MODE == OrderMode.COMMIT) {
            // 提交模式
            Wmlsbjb wmlsbjb = getDb().wmlsbjbDao().findOne();
            if (wmlsbjb != null) {
                mBinding.titleView.setText(String.format(Locale.CHINA, "单号:%s\n桌号:%s",
                        wmlsbjb.getWmdbh(), wmlsbjb.getZh().replace(",", "")));

            } else {
                mBinding.titleView.setText("我的订单");
            }
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            params.addRule(RelativeLayout.ALIGN_PARENT_END);
            mBinding.moneyView.setLayoutParams(params);

            mBinding.quickLayout.setVisibility(View.GONE);
            mBinding.commitLayout.setVisibility(View.VISIBLE);
            //--
            mBinding.continueButton.setOnClickListener(v -> {
                if (mOnClickListener != null) {
                    mOnClickListener.gotoMenuFragment();
                }
            });

            mBinding.commitButton.setOnClickListener(v -> {
                new OrderCommit().orderCommitToSqlServer(new OrderCommit.OnStatusListener() {
                    @Override
                    public void onSuccess() {
                        EventBus.getDefault().post(new ToastEvent("订单提交成功", false));
                    }

                    @Override
                    public void onFail() {
                        EventBus.getDefault().post(new ToastEvent("订单提交失败", false));
                    }
                });
            });

        } else {
            //自助屏模式
            mBinding.titleView.setVisibility(View.GONE);
            mBinding.quickLayout.setVisibility(View.VISIBLE);
            mBinding.commitLayout.setVisibility(View.GONE);

            // 扫描进入
            if (ChoiceType.SCAN == Settings.CHOICE_TYPE) {
                mBinding.scanEditText.setOnEditorActionListener(mScanOnEditorActionListener);
                mBinding.scanPromptView.setVisibility(View.VISIBLE);
                // mBinding.addButton.setVisibility(View.GONE);
                mBinding.backButton.setVisibility(View.VISIBLE);
                mBinding.backButton.setOnClickListener(v -> {
                    if (mOnClickListener != null) {
                        mOnClickListener.onBackClick();
                    }
                });
            }

            //--
            mBinding.addButton.setOnClickListener(v -> {
                if (mOnClickListener != null) {
                    mOnClickListener.gotoMenuFragment();
                }
            });

            mBinding.clearButton.setOnClickListener(v -> {
                if (getFragmentManager() != null && OrderList.getInstance().getOrderItemList().size() > 0) {
                    PromptDialogFragment fragment = PromptDialogFragment.newInstance(
                            "清空购物车?", false);
                    fragment.setOnBtnClickListener(new PromptDialogFragment.OnBtnClickListener() {
                        @Override
                        public void onCancelBtnClick() {
                        }

                        @Override
                        public void onOkBtnClick() {
                            OrderList.getInstance().clear(list -> {

                                if (ChoiceType.SCAN != Settings.CHOICE_TYPE) {
                                    if (mOnClickListener != null) {
                                        mOnClickListener.gotoMenuFragment();
                                    }
                                }
                            });
                        }
                    });

                    fragment.show(getFragmentManager(), null);
                }
            });

            mBinding.payButton.setOnClickListener(v -> {
                if (OrderList.getInstance().getOrderItemList().size() > 0) {
                    if (mOnClickListener != null) {
                        mOnClickListener.onPayOrderClick();
                    }
                } else {
                    EventBus.getDefault().post(new ToastEvent("请先下单,再买单", false));
                }
            });
        }

        if (mFromCloud) {
            mBinding.payButton.setText("返回云会员");
        }

        //
        refreshDataSync();
    }

    @Override
    public void onStart() {
        super.onStart();
        OrderList.getInstance().addObserver(mOrderObserver);
    }

    @Override
    public void onStop() {
        super.onStop();
        OrderList.getInstance().deleteObserver(mOrderObserver);
    }

    public void refreshDataSync() {
        OrderList.getInstance().refreshData(this::refreshData);
    }

    public void refreshData(List<OrderItem> list) {
        mBinding.moneyView.setPrice(OrderList.getInstance().getMoney().getReceivableFloat());

        if (mBinding.recyclerView.getAdapter() == null) {
            mAdapter = new OrderAdapter(this, list);
            mBinding.recyclerView.setAdapter(mAdapter);
        } else {
            mAdapter.updateData(list);
        }

        if (list.size() == 0 && ChoiceType.SCAN != Settings.CHOICE_TYPE) {
            if (mOnClickListener != null) {
                mOnClickListener.gotoMenuFragment();
            }
        }

        // 扫描模式下
        if (ChoiceType.SCAN == Settings.CHOICE_TYPE) {
            // 列表滚动到最下面
            if (mScroll && mAdapter.getItemCount() > 1) {
                mScroll = false;
                mBinding.recyclerView.smoothScrollToPosition(mAdapter.getItemCount() - 1);
            }

            if (list.size() == 0) {
                mBinding.scanPromptView.setVisibility(View.VISIBLE);
            } else {
                mBinding.scanPromptView.setVisibility(View.GONE);
            }
        }
    }

    public void setOnClickListener(OnClickListener onClickListener) {
        mOnClickListener = onClickListener;
    }

    private OnClickListener mOnClickListener;

    public interface OnClickListener {

        void onPayOrderClick();

        void gotoMenuFragment();

        void onBackClick();
    }
}
